package com.lagou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 连接工具类: 从数据源中获取一个连接，并将该连接与线程进行绑定
 */
@Component
public class ConnectionUtils {

    @Autowired
    private DataSource dataSource;

    private ThreadLocal<Connection> threadLocal = new ThreadLocal();

    /**
     * 获取当前线程上绑定连接，如果为空，就从数据源中获取，并且放到ThreadLocal中(绑定到当前线程)
     */
    public Connection getThread(){
        // 1.先从ThreadLocal线程类中获取连接对象
        Connection connection = threadLocal.get();
        if (connection==null){
            try {
                // 2.从数据源中获取连接对象
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 解除当前线程的连接绑定
     */
    public void removeThreadConnection(){
        threadLocal.remove();
    }
}
